<?php

namespace App\Repositories;

use App\Exceptions\BusinessException;
use App\Models\User\UserModel as User;
use App\Models\User\UserModel;
use App\Models\User\UserOrdersModel;
use App\Models\User\UserSearchLogModel;
use App\Models\UserStaffModel;
use DB;
use App\Models\Admin\UserAccessModel;

class UserRepository
{
    protected $user;
    protected $user_search;
    protected $user_order_mdl;
    protected $user_access;
    protected $user_staff;

    public function __construct()
    {
        $this->user = new User();
        $this->user_search = new UserSearchLogModel();
        $this->user_order_mdl = new UserOrdersModel();
        $this->user_access = new UserAccessModel();
        $this->user_staff = new UserStaffModel();
    }

    /**
     * 根据用户ID查询用户信息
     * @param $id
     * @return mixed
     */
    public function getUserById($id)
    {
        return $this->user->where('id', '=', $id)->first();
    }

    /**
     * 根据手机号查询用户信息
     * @param string $phone
     * @return mixed
     */
    public function getUserByPhone($phone='')
    {
        return $this->user->where('phone', '=', $phone)->first();
    }

    /**
     * 查询用户搜索记录
     * @param string $phone
     * @return mixed
     */
    public function getUserSearchKeywords($uid=0)
    {
        $keywords = $this->user_search->where(['uid'=> $uid,'platform'=>1])->orderBy('created_at','desc')->limit(10)->get(['id','keywords']);
        return $keywords->isEmpty() ? [] : $keywords->toArray();
    }

    /**
     * 保存用户搜索记录
     * @param string $phone
     * @return mixed
     */
    public function addUserSearchKeywords($uid=0,$username='',$keyword='')
    {
        return $this->user_search->insertGetId([
            'uid'=>$uid,
            'username'=>$username,
            'platform'=>1,
            'keywords'=>$keyword,
            'created_at'=>time()
        ]);
    }

    /**
     * 获取用户订单
     * @param string $phone
     * @return mixed
     */
    public function getOrders($uid=0,$offset=0,$pageSize=20)
    {
        $keywords = $this->user_order_mdl->where(['uid'=> $uid,'user_delete'=>0])->orderBy('created_at','desc')->skip($offset)->take($pageSize)->get();
        return $keywords->isEmpty() ? [] : $keywords->toArray();
    }

    /**
     * 删除用户订单
     * @param string $phone
     * @return mixed
     */
    public function delOrders($uid=0,$oid=0)
    {
        DB::beginTransaction();
        try {
            if($this->user_order_mdl->where(['id'=>$oid,'uid'=>$uid])->update([
                'user_delete'=>1
            ])){
                DB::commit();
                return true;
            }else{
                DB::rollback();
                return false;
            }
        } catch (\Exception $e) {
            \Log::error($e->getMessage());
            DB::rollback();
        }
    }

    /**
     *  创建用户记用
     */
    public function addUser($name, $phone, $password)
    {
        $ti = time();
        $this->user->setRawAttributes([
            'name' => $name,
            'phone' => $phone,
            'password' => md5($password),
            'created_at' => $ti,
            'updated_at' => $ti,
        ]);
        if (!$this->user->save()) {
            throw new BusinessException('create user fail', 10001);
        };
        return $this->user->getAttribute('id');
    }

    /**
     * 创建登录记录
     * @param $uid
     * @param array $content
     * @return string
     * @throws BusinessException
     */
    public function addUserAccess($uid, array $content)
    {
        $token = md5($uid.str_random().time());
        $ti = time();
        $ret = $this->user_access->setRawAttributes([
            'token' => $token,
            'content' => json_encode($content, true),
            'created_at' => $ti,
            'updated_at' => $ti,
            'effective_time' => $ti+3600
        ])->save();
        if ($ret) {
            return $token;
        }
        throw new BusinessException('登录失败', 20001);
    }

    public function update(UserModel $user, array $data)
    {
        return $user->update($data);
    }
}